#include "mysqlqt.h"
#include <QtSql/QSqlDatabase>
#include <qdebug.h>
#include <QSqlQuery>
#include <QStringList>
#include <QSqlRecord>

MySqlQt::MySqlQt()
{
    db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("127.0.0.1");
    db.setDatabaseName("qtdatabase");
    db.setUserName("root");
    db.setPassword("597522");
    db.setPort(3306);
}

MySqlQt::~MySqlQt()
{

}

void MySqlQt::ConnectSql(QSqlDatabase db)
{
    bool ok = db.open();
    if(ok)
    {
        qDebug() << "databse connect is ok";
    }
    else
    {
        qDebug() << "databse connect is fail";
    }
}

void MySqlQt::InsertUserName(QSqlDatabase db, const QString &name, const QString &paw)
{
    QSqlQuery query(db);
    query.prepare("INSERT INTO usertable VALUES(:username,:userpaw)");
    query.bindValue(":username",name);
    query.bindValue(":userpaw",paw);
    query.exec();
    query.finish();
}

QString MySqlQt::SelectUserPaw(QSqlDatabase db, const QString &name)
{
    QSqlQuery query(db);
    QString Sql_str = "SELECT userpaw FROM usertable WHERE username = :username";
    query.prepare(Sql_str);
    query.bindValue(":username",name);
    query.exec();
    query.next();
    QString paw = query.value(0).toString();
   // qDebug() << query.value(0).toString();
     query.finish();
    return paw;

}

void MySqlQt::InsertEquInf(QSqlDatabase db, const QString &name, const QString &ManFact, const QString &Id, const QString &Rang, const QString &Singal)
{
    QSqlQuery query(db);
    QString Sql_str = "INSERT INTO sensortable VALUES(:name,:ManFact,:Moder,:Range,:Singal)";
    query.prepare(Sql_str);
    query.bindValue(":name",name);
    query.bindValue(":ManFact",ManFact);
    query.bindValue(":Moder",Id);
    query.bindValue(":Range",Rang);
    query.bindValue(":Singal",Singal);
    query.exec();
    query.finish();
}

// by ManFact Id find EquiInf
SensorData* MySqlQt:: SelectEquiById(QSqlDatabase db,QString ID)
{
    QString Name;
    QString ManFact;
    QString model;
    QString rangeNum;
    QString singal;
    QString Sql_str = QString("SELECT * FROM sensortable WHERE MODEL = %1;").arg(ID);
    QSqlQuery query(Sql_str,db);
    while(query.next())
    {
        Name = query.value("name").toString();
        ManFact = query.value("manfact").toString();
        model = query.value("model").toString();
        rangeNum = query.value("rangeNum").toString();
        singal = query.value("singal").toString();
      //  qDebug() << Name;
    }
    SensorData* sen = new SensorData(Name,ManFact,model,rangeNum,singal);
    if(sen==nullptr)
    {
        qDebug() << "Sensor is Eoor";
        return NULL;
    }
    else
    {
        return sen;
    }
}
